package lt.egidijus.aatest.wizards;

import lt.egidijus.aatest.listener.NewProjectListener;
import lt.egidijus.aatest.utils.Constants;
import lt.egidijus.aatest.utils.Utils;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;

import com.android.ide.eclipse.adt.internal.wizards.newproject.NewTestProjectWizard;

@SuppressWarnings("restriction")
public class NewAATestWizard extends NewTestProjectWizard {
	
	public NewAATestWizard() {
		super();
	}
	
	
	@Override
	public boolean performFinish() {
		IResourceChangeListener listener = new NewProjectListener();
		   ResourcesPlugin.getWorkspace().addResourceChangeListener(listener,
		      IResourceChangeEvent.POST_CHANGE);
		super.performFinish(); 
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		ResourcesPlugin.getWorkspace().removeResourceChangeListener(listener);
//		Path path = new Path("lib\\jacocoagent.jar");
//		Bundle bundle = Platform.getBundle( "AATestPlugin" );
//		InputStream stream = null;
//		try {
//			stream = FileLocator.openStream( bundle, path, false );
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		//delete from test project blogus failus
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(Constants.testProjectName);
		IJavaProject projectJava = JavaCore.create(project);
		IFolder srcFolder = project.getProject().getFolder("src");
		IPackageFragmentRoot src = projectJava.getPackageFragmentRoot(srcFolder);
		try {
			IJavaElement[] elements = src.getChildren();
		     IResource res =  elements[1].getCorrespondingResource();
		     res.delete(IResource.FORCE, null);
		} catch (JavaModelException e1) {
			e1.printStackTrace();
		} catch (CoreException e) {
			e.printStackTrace();
		}
		
		
//		IFolder f = project.getProject().getFolder("lib");
//		if (!f.exists()) {
//			try {
//				f.create(true, true, null);
//			} catch (CoreException e) {
//				e.printStackTrace();
//			}
//		}
//		IFile file = project.getFile( "lib\\jacocoagent.jar" );
//		try {
//			file.create( stream, true, null );
//		} catch (CoreException e) {
//			e.printStackTrace();
//		}
		Utils.createCoverageFolder();
		return true;
	}
	
	

}
